/**
 * 日志管理器
 * 🔥 自动收集所有日志并上传到服务器
 */
const log = require('electron-log');
const path = require('path');
const { app } = require('electron');

class Logger {
  constructor() {
    // 配置日志文件
    log.transports.file.level = 'info';
    log.transports.file.maxSize = 10 * 1024 * 1024; // 10MB
    log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}';
    
    const logPath = path.join(app.getPath('userData'), 'logs');
    log.transports.file.resolvePathFn = () => path.join(logPath, 'main.log');

    // 控制台输出
    log.transports.console.level = 'debug';
    log.transports.console.format = '[{h}:{i}:{s}] [{level}] {text}';

    this.log = log;
    this.logUploader = null; // 延迟加载避免循环依赖
  }
  
  /**
   * 🔥 设置日志上传器
   */
  setLogUploader(uploader) {
    this.logUploader = uploader;
  }

  /**
   * 🔥 添加日志到上传队列
   */
  addToUploadQueue(level, message, stack = null) {
    if (this.logUploader) {
      this.logUploader.addLog(level, message, stack);
    }
  }

  info(message, ...args) {
    this.log.info(message, ...args);
    // 🔥 添加到上传队列
    this.addToUploadQueue('info', message);
  }

  error(message, ...args) {
    this.log.error(message, ...args);
    // 🔥 添加到上传队列（包含错误堆栈）
    const errorObj = args[0];
    const stack = (errorObj instanceof Error) ? errorObj.stack : null;
    this.addToUploadQueue('error', message, stack);
  }

  warn(message, ...args) {
    this.log.warn(message, ...args);
    // 🔥 添加到上传队列
    this.addToUploadQueue('warning', message);
  }

  debug(message, ...args) {
    this.log.debug(message, ...args);
    // 🔥 优化：debug日志不上传到服务器，减少CPU占用和网络流量
    // this.addToUploadQueue('debug', message);
  }

  // 记录传输日志
  logTransfer(type, fileName, status, details = {}) {
    const message = `[传输] ${type.toUpperCase()} - ${fileName} - ${status}`;
    this.info(message, details);
  }

  // 记录FTP操作
  logFTP(action, details = {}) {
    const message = `[FTP] ${action}`;
    this.info(message, details);
  }

  // 记录WebSocket操作
  logWebSocket(action, details = {}) {
    const message = `[WebSocket] ${action}`;
    this.info(message, details);
  }

  // 记录认证操作
  logAuth(action, username, success, error = null) {
    const message = `[认证] ${action} - ${username} - ${success ? '成功' : '失败'}`;
    if (success) {
      this.info(message);
    } else {
      this.error(message, error);
    }
  }

  // 获取日志文件路径
  getLogPath() {
    return log.transports.file.getFile().path;
  }
}

module.exports = new Logger();
